<template>
  <div class="com-container">
    <div class="com-chart" ref="rank_ref"></div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, onMounted, onUnmounted, nextTick } from "vue";
import axios from "axios";
import { getThemeValue } from "@/utils/theme_utils.ts";
import { useThemeChart } from "@/hooks/useThemeChart.ts";

const { proxy } = getCurrentInstance()!;
const rank_ref = ref();
const allData = ref([]);
const echartsInstance = ref(null);
const startValue = ref(0); // 区域缩放的起点值
const endValue = ref(9); // 区域缩放的终点值
const timerId = ref(null);

// 初始化echartsInstance对象
const initChart = () => {
  echartsInstance.value = proxy!.$echarts.init(rank_ref.value, themeStore.theme);
  // 对图表初始化配置的控制
  const initOption = {
    title: {
      text: "▎ 地区销售排行",
      left: 20,
      top: 20
    },
    grid: {
      top: "40%",
      left: "5%",
      right: "5%",
      bottom: "5%",
      containLabel: true
    },
    backgroundColor: getThemeValue(themeStore.theme).bgColor,
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      type: "category"
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        type: "bar",
        label: {
          show: true,
          position: "top"
        }
      }
    ]
  };
  echartsInstance.value.setOption(initOption);
  // 对图表对象进行鼠标事件的监听
  echartsInstance.value.on("mouseover", () => {
    clearInterval(timerId.value);
  });
  echartsInstance.value.on("mouseout", () => {
    startInterval();
  });
};

// 获取服务器的数据
const getData = async () => {
  const { data: res } = await axios.get("http://127.0.0.1:8888/api/rank");
  allData.value = res;
  // 对数据排序
  allData.value.sort((a, b) => {
    return b.value - a.value; // 从大到小的排序
  });
  updateChart();
  // 启动定时器
  startInterval();
};

// 更新图表
const updateChart = () => {
  const colorArr = [
    ["#0BA82C", "#4FF778"],
    ["#2E728F", "#23E5E5"],
    ["#5052EE", "#AB6EE5"]
  ];
  // 所有省份形成的数组
  const provinceArr = allData.value.map(item => {
    return item.name;
  });
  // 所有省份对应的销售金额
  const valueArr = allData.value.map(item => {
    return item.value;
  });
  const dataOption = {
    dataZoom: {
      show: false,
      startValue: startValue.value,
      endValue: endValue.value
    },
    xAxis: {
      data: provinceArr
    },
    series: [
      {
        data: valueArr,
        itemStyle: {
          color: arg => {
            let targetColorArr = null;
            if (arg.value > 200) {
              targetColorArr = colorArr[0];
            } else if (arg.value > 100) {
              targetColorArr = colorArr[1];
            } else {
              targetColorArr = colorArr[2];
            }
            return new proxy!.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: targetColorArr[0]
              },
              {
                offset: 1,
                color: targetColorArr[1]
              }
            ]);
          }
        }
      }
    ]
  };
  echartsInstance.value.setOption(dataOption);
};

const startInterval = () => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  timerId.value = window.setInterval(() => {
    startValue.value++;
    endValue.value++;
    if (endValue.value > allData.value.length - 1) {
      startValue.value = 0;
      endValue.value = 9;
    }
    updateChart();
  }, 2000);
};

const screenAdapter = () => {
  const titleFontSize = (rank_ref.value.offsetWidth / 100) * 3.6;
  // 和分辨率大小相关的配置项(适配文字标题的大小)
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: titleFontSize
      }
    },
    tooltip: {
      show: true,
      trigger: "axis"
    },
    series: [
      {
        barWidth: titleFontSize,
        itemStyle: {
          borderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0] // 设置圆角的大小
        }
      }
    ]
  };
  echartsInstance.value.setOption(adapterOption);
  // 手动的调用图表对象的resize 才能产生效果
  echartsInstance.value.resize();
};

const { themeStore } = useThemeChart(echartsInstance, initChart, updateChart);

onMounted(async () => {
  try {
    proxy.$socket.registerCallBack("rankData", getData);
    await nextTick();
    initChart();
    proxy.$socket.send({
      action: "getData",
      socketType: "rankData",
      chartName: "rank",
      value: ""
    });
    window.addEventListener("resize", screenAdapter);
  } catch (error) {
    console.error("Mounted hook error:", error);
  }
});

onUnmounted(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  // 在组件销毁的时候, 需要将监听器取消掉
  window.removeEventListener("resize", screenAdapter);
  // 注销回调（使用可选链操作符）
  proxy.$socket.unRegisterCallBack("rankData");
});

defineExpose({
  screenAdapter
});
</script>
